package org.springframework.jdbc.core;

import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.util.StringUtils;

public class BeanPropertyMapRowMapper extends ColumnMapRowMapper {

	/**
	 * Convert a name in camelCase to an underscored name in lower case. Any
	 * upper case letters are converted to lower case with a preceding
	 * underscore.
	 * 
	 * @param name
	 *            the original name
	 * @return the converted name
	 * @since 4.2
	 */
	protected String toCaseName(String name) {
		if (!StringUtils.hasLength(name)) {
			return "";
		}
		name = name.toLowerCase();

		StringBuilder result = new StringBuilder(name.length());
		boolean upperCase = false;
		for (int i = 0; i < name.length(); i++) {
			char c = name.charAt(i);
			if (c == '_') {
				upperCase = true;
			} else if (upperCase) {
				result.append(Character.toUpperCase(c));
				upperCase = false;
			} else {
				result.append(c);
			}
		}

		return result.toString();
	}

	/**
	 * Determine the key to use for the given column in the column Map.
	 * 
	 * @param columnName
	 *            the column name as returned by the ResultSet
	 * @return the column key to use
	 * @see java.sql.ResultSetMetaData#getColumnName
	 */
	@Override
	protected String getColumnKey(String columnName) {
		return toCaseName(columnName);
	}
}
